//
//  BankCardViewController.m
//  Kjs-iOS
//
//  Created by 江伟 on 16/6/22.
//  Copyright © 2016年 jmhz. All rights reserved.
//

#import "BankCardViewController.h"
#import "BankCardTableViewCell.h"
#import "AddBankCardViewController.h"
#import "DelBindView.h"
#import "AppDelegate.h"
#import "KJSRequest.h"
#import <MJRefresh.h>
#import "BankCard.h"
#define screenW [[UIScreen mainScreen] bounds].size.width //屏幕宽度
#define screenH [[UIScreen mainScreen] bounds].size.height //屏幕高度

@interface BankCardViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,strong) NSMutableArray <BankCard *> *bankCardList;
@property (nonatomic,assign) NSInteger cellNum;
@property (nonatomic,strong) UIView *contantV;
@property (nonatomic,strong) NSString *bankCardId;
@property (nonatomic,strong) DelBindView *delBindView;
@property (nonatomic,strong) BasicResult *result;
@end

@implementation BankCardViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"银行卡管理"];
    self.bankCardTableView.delegate = self;
    self.bankCardTableView.dataSource = self;
//    去掉分割线
    self.bankCardTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.addBankView  = [[[NSBundle mainBundle] loadNibNamed:@"AddBankView" owner:self options:nil] firstObject];
    self.addBankView.goAddBankCard = ^(void){
        [self goAddBankCard];
    };
    self.bankCardTableView.tableFooterView = self.addBankView;
    
//    UITapGestureRecognizer *goAddBankCard = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(goAddBankCard)];
//    self.addBankView.userInteractionEnabled = YES;
//    [self.addBankView  addGestureRecognizer:goAddBankCard];
    [self.addBankView.addBankBtn addTarget:self action:@selector(goAddBankCard) forControlEvents:UIControlEventTouchUpInside];
    
    self.delBindView = [[[NSBundle mainBundle] loadNibNamed:@"DelBindView" owner:self options:nil] firstObject];
    self.delBindView.layer.cornerRadius = 15;
    self.delBindView.layer.masksToBounds = YES;
    self.delBindView.cancelBtn.tag = 0;
    [self.delBindView.cancelBtn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];
    self.delBindView.confirmBtn.tag = 1;
    [self.delBindView.confirmBtn addTarget:self action:@selector(clickButton:) forControlEvents:UIControlEventTouchUpInside];

    [self configeration];
    [self configurateTableView];
    
    self.contantV = [[UIView alloc] initWithFrame:CGRectMake(0, screenH, screenW, screenW)];
    self.contantV.backgroundColor = [[UIColor darkGrayColor] colorWithAlphaComponent:0.8];

    [self.view addSubview:self.contantV];

    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.addBankView.addBankView setBackgroundColor:[UIColor whiteColor]];
    if ([self.bankCardList count] == 0) {
        [self GetBankCardList];
    }
}
#pragma mark - configeration
- (void)configeration
{
    self.bankCardList = [[NSMutableArray alloc] init];
    self.cellNum = 0;
    self.delBindView.pswTF.text = @"";
}
- (void)configurateTableView {
    self.bankCardTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
}

#pragma mark - custom method
- (void)GetBankCardList
{
    if (CurentDelegate.account) {
        [KJSRequest GetBankCardListWithPartyId:CurentDelegate.account.partyId ret:^(BankCardModel *model) {
            [self.bankCardList addObjectsFromArray:model.bankCardList];
            self.cellNum = [self.bankCardList count];
            [self endRefresh];
            //排序,将主卡放在第一个
            for (int i = 0; i < [self.bankCardList count]; i++) {
                if ([self.bankCardList[i].isMainTradeCard isEqualToString:@"1"]) {
                    BankCard *temp = self.bankCardList[i];
                    self.bankCardList[i] = self.bankCardList[0];
                    self.bankCardList[0] = temp;
                    break;
                }
            }
            [self.bankCardTableView reloadData];

        }];
    }
}

- (void)RemoveBank
{
    if (CurentDelegate.account) {
        NSLog(@"bankId=%@,tradepsw=%@",self.bankCardId,self.delBindView.pswTF.text);
        [KJSRequest RemoveAppBankCardWithPartyId:CurentDelegate.account.partyId bankCardId:self.bankCardId tradePwd:self.delBindView.pswTF.text ret:^(BasicResult *model) {
            self.result = model;
            if ([self.result.messageEncode isEqualToString:@"MG013103"]) {
                [self.view endEditing:YES];
                [self.bankCardTableView beginUpdates];
                [self configeration];
                [self GetBankCardList];
                [self.bankCardTableView endUpdates];
//                [self.bankCardTableView reloadData];
                [UIView animateWithDuration:0.5 animations:^{
                    self.contantV.frame = CGRectMake(0, screenH, screenW, screenH);
                }];
               
            }
            [GUATool showDialog:self.result.msg message:nil waitingTime:1.5];
        }];
    }
}
        
- (void) goAddBankCard
{
    NSLog(@"跳转到添加银行卡界面");
    if ([CurentDelegate.account.levels intValue] < 1) {
        [GUATool showDialog:@"请先进行实名认证" message:nil waitingTime:1.5];
    }else{
        AddBankCardViewController *addBankCardVC = [[UIStoryboard storyboardWithName:@"Seconed" bundle:nil] instantiateViewControllerWithIdentifier:@"AddBankCardViewController"];
        [self.addBankView.addBankView setBackgroundColor:[UIColor colorWithRed:245/255.0f green:245/255.0f blue:245/255.0f alpha:1]];
        addBankCardVC.addSuccess = ^(){
            [self configeration];
        };
        [self displayViewController:addBankCardVC];
    }
}
- (void) showDelBindView:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    if (btn.tag == 0) {
        [GUATool showDialog:@"不能解绑主卡" message:nil waitingTime:1.5];
    }else{
        NSLog(@"展示解除绑定对话框");
        self.bankCardId = ((BankCard *)self.bankCardList[btn.tag]).bankCardId;
        self.delBindView.pswTF.text = @"";
        NSLog(@"bankCardId%@",self.bankCardId);
        UIView *contantV = [[UIView alloc] initWithFrame:CGRectMake((screenW - self.delBindView.frame.size.width)/2, (screenW - self.delBindView.frame.size.height - 40)/2, self.delBindView.frame.size.width, self.delBindView.frame.size.height)];
        [contantV addSubview:self.delBindView];
        [self.contantV addSubview:contantV];
        [UIView animateWithDuration:0.5 animations:^{
            self.contantV.frame = CGRectMake(0, 0, screenW, screenH);
        }];
    }
   
    
}
-(void)clickButton:(id)sender
{
    UIButton *btn = (UIButton *)sender;
    switch (btn.tag) {
        case 0:
        {
            NSLog(@"取消");
            [UIView animateWithDuration:0.5 animations:^{
                self.contantV.frame = CGRectMake(0,screenH, screenW, screenH);
            }];
        }
            break;
        case 1:
            NSLog(@"确定");
            if ([self.delBindView.pswTF.text isEqualToString:@""]) {
                [GUATool showDialog:@"请输入交易密码" message:nil waitingTime:1.5];

            }else{
                [self RemoveBank];
            }
            break;
        default:
            break;
    }
}
-(void)setMainBankCard
{
    if (CurentDelegate.account.partyId) {
        [KJSRequest setAppDefaultCardWithPartyId:CurentDelegate.account.partyId bankCardId:self.bankCardId ret:^(BasicResult *model) {
            if (model.success) {
                [GUATool showDialog:@"设置主卡成功" message:nil waitingTime:1.5];
                [self configeration];
                [self GetBankCardList];
                [UIView performWithoutAnimation:^{
                    [self.bankCardTableView reloadData];
                }];
//                [self.bankCardTableView reloadData];
            }
        }];
    }
}
#pragma mark - UITableViewSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.cellNum;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BankCardTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BankCardTableViewCell"];
    cell.bankCard = self.bankCardList[indexPath.row];
    cell.delBindBtn.tag = indexPath.row;
    [cell.delBindBtn addTarget:self action:@selector(showDelBindView:) forControlEvents:UIControlEventTouchUpInside];
    cell.setMainCardOperate = ^(NSString *bankCardId){
        self.bankCardId = bankCardId;
        [self setMainBankCard];
    };
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

#pragma mark - refresh method
- (void)headerRefresh {
    [self configeration];
    [self GetBankCardList];
}

- (void)endRefresh {
    [self.bankCardTableView.mj_header endRefreshing];
}

@end
